package com.byzk.p2p.app.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.byzk.p2p.admin.bank.dto.Bank;
import com.byzk.p2p.admin.bank.dto.BankCard;
import com.byzk.p2p.admin.bank.service.BankCardService;
import com.byzk.p2p.admin.bank.vo.BankCardVo;
import com.byzk.p2p.admin.base.controller.BaseController;
import com.byzk.p2p.admin.base.util.Constant;
import com.byzk.p2p.admin.base.util.JsonMsg;
import com.byzk.p2p.admin.base.util.MD5;
import com.byzk.p2p.admin.base.util.PageInfo;
import com.byzk.p2p.admin.base.util.QRcode;
import com.byzk.p2p.admin.base.util.RequestUtil;
import com.byzk.p2p.admin.base.util.SHA;
import com.byzk.p2p.admin.city.dto.City;
import com.byzk.p2p.admin.city.service.CityService;
import com.byzk.p2p.admin.money.service.BorrowPaymentDetailService;
import com.byzk.p2p.admin.money.service.FundRecordService;
import com.byzk.p2p.admin.money.service.WithdrawService;
import com.byzk.p2p.admin.money.vo.BorrowPaymentDetailVo;
import com.byzk.p2p.admin.money.vo.SumWithdrawVo;
import com.byzk.p2p.admin.money.vo.WithdrawRecordVo;
import com.byzk.p2p.admin.red.service.RedEnveService;
import com.byzk.p2p.admin.red.vo.RedEnveVo;
import com.byzk.p2p.admin.system.dto.SystemConfig;
import com.byzk.p2p.admin.system.service.SMSService;
import com.byzk.p2p.admin.system.service.SystemService;
import com.byzk.p2p.admin.user.dto.InviteRef;
import com.byzk.p2p.admin.user.dto.User;
import com.byzk.p2p.admin.user.dto.UserAccount;
import com.byzk.p2p.admin.user.dto.UserAuth;
import com.byzk.p2p.admin.user.service.UserAccountService;
import com.byzk.p2p.admin.user.service.UserAuthService;
import com.byzk.p2p.admin.user.service.UserService;
import com.byzk.p2p.admin.user.vo.InviteRefVo;
import com.byzk.p2p.admin.user.vo.UserAccountVo;
import com.byzk.p2p.front.service.FrontUserService;
import com.byzk.p2p.front.session.UserSession;

/**
 * app端用户操作
 * @author suker.zhou
 */
@Controller
@RequestMapping("/app")
@Scope("prototype")
public class AppUserController extends BaseController {

	private static final Logger log = LoggerFactory.getLogger(AppUserController.class);
	
	@Autowired
	private UserService userService;

	@Autowired
	private BankCardService bankCardService;
	
	@Autowired
	private SMSService sMSService;
	
	@Autowired
	private UserAccountService userAccountService;
	
	@Autowired
	private UserAuthService userAuthService;
	
	@Autowired
	private RedEnveService redEnveService;
	
	@Autowired
	private BorrowPaymentDetailService borrowPaymentDetailService;
	
	@Autowired
	private FrontUserService frontUserService;
	
	@Autowired
	private SystemService systemService;
	
	@Autowired
	private FundRecordService fundRecordService;
	
	@Autowired
	private CityService cityService;
	
	@Autowired
	private WithdrawService withdrawService;
	
	/**
	 * app用户登录接口
	 * 	
	 * @param info 接受对象	
	 * @throws Exception  抛出异常	
	 */
	@RequestMapping(value = "/login")
	public void login(@ModelAttribute User info) throws Exception {
		Map<String, String> jsonMap = new HashMap<String, String>();
		if (info.getUsername() == null || info.getUsername().equals("")) {
			super.printJSON(new JsonMsg(1, "用户名不能为空！"));
			return;
		}
		if (info.getPassword() == null || info.getPassword().equals("")) {
			super.printJSON(new JsonMsg(2, "用户密码不能为空！"));
			return;
		}
		
		User temp = userService.selectByNameOrPhone(info.getUsername());
		if (temp==null) {
			super.printJSON(new JsonMsg(3, "用户名还未注册!"));
			return;
		} else {
			if(!temp.getPassword().equals(MD5.GetMD5Code(info.getPassword()))){
				super.printJSON(new JsonMsg(4, "密码输入错误!"));
				return;
			}
			if("Y".equals(temp.getStatus())){
				super.printJSON(new JsonMsg(5, "账户已锁定,请联系客服"));
				return;
			}			
			Integer loginCount = temp.getLoginCount();
			temp.setLoginCount(loginCount == null?1:++loginCount);
			temp.setLastIp(RequestUtil.getRemortIP(request));
			temp.setLastTime(new Date());
			
			UserAccountVo account = new UserAccountVo();
			account.setUserId(temp.getId());
			jsonMap.put("balance", userAccountService.listAll(account).getPageList().get(0).getBalance().toString());
			jsonMap.put("uid", temp.getId().toString());
			jsonMap.put("phone", temp.getPhone());
			jsonMap.put("isnew", temp.getIsnew());
			jsonMap.put("realname", temp.getRealname());
			jsonMap.put("username", temp.getUsername());
			jsonMap.put("fuionAccount", temp.getFuionAccount());
			super.printJSON(new JsonMsg(-1, "登录成功", jsonMap));
			return;
		}
	}
	
	
	
	/**
	 * 验证手机号是否唯一
	 * @param info
	 * @throws Exception
	 */
	@RequestMapping(value = "/phone/check")
	public void checkPhone(@ModelAttribute User info) throws Exception{
		if (info == null || info.getPhone() == null) {
			super.printJSON(new JsonMsg(1, "手机号不能为空！"));
			return;
		}
		List<User> list = userService.getByUser(info);
		if (list.size() > 0) {
			super.printJSON(new JsonMsg(2, "该手机号已经存在！"));
			return;
		}
		super.printJSON(new JsonMsg(-1, "验证成功！"));
	}

	/**
	 * app短信接口
	 * @param info 接受对象
	 * @throws Exception  抛出异常
	 */
	@RequestMapping(value = "/sms/send")
	public void sendSms(@ModelAttribute User info) throws Exception {
		if(StringUtils.isBlank(info.getPhone())) {
			super.printJSON(new JsonMsg(1, "手机号不能为空！"));
			return;
		}
		List<User> list = userService.getByUser(info);
		if (list.size() > 0) {
			super.printJSON(new JsonMsg(2, "该手机号已经存在！"));
			return;
		}
		String imgCode = request.getParameter("imgCode");
		if(StringUtils.isBlank(imgCode)) {
			super.printJSON(new JsonMsg(1, "图形验证码不能为空！"));
			return;
		}
		String sessionCode = (String) request.getSession().getAttribute("jcaptchaCode");
		if(!imgCode.equals(sessionCode)) {
			super.printJSON(new JsonMsg(5, "图形验证码输入有误！"));
			return;
		}
		Map<String, String> jsonMap = new HashMap<String, String>();
		
		int intCount = 0;
		intCount = new Random().nextInt(9999);
		if (intCount < 1000) {
			intCount += 1000;
		}
//		String randomCode = "" + intCount;
		String randomCode = "0000";
		
//		sMSService.sendCaptchaCodeSms(info.getPhone(),randomCode,request.getRemoteAddr());
		// md5加密验证码给前台
		jsonMap.put("randomCode", SHA.encryptPassword(randomCode+info.getPhone()));
		jsonMap.put("phone", info.getPhone());
		super.printJSON(new JsonMsg(-1, "发送成功", jsonMap));
	}

	/**
	 * app端用户注册接口
	 * 
	 * @param info 接受对象
	 * @param code 输入的验证码
	 * @param randomCode 手机验证码
	 * @throws Exception  抛出异常
	 */
	@RequestMapping(value = "/register")
	public void register( @RequestParam("phone") String phone,
						  @RequestParam("password") String password, 
						  @RequestParam("code") String code,
			              @RequestParam("randomCode") String randomCode,
			              @RequestParam("terminal") String terminal,
			              @RequestParam(value="inviteCode",required=false) String inviteCode) throws Exception {
		// app端注册手机号及为用户名
		if (StringUtils.isBlank(phone)) {
			super.printJSON(new JsonMsg(3, "手机号不能为空！"));
			return;
		}		
		if(code==null || code.equals("")){
			super.printJSON(new JsonMsg(1, "请填写验证码！"));
			return;
		}
		if (!randomCode.equals(SHA.encryptPassword(code+phone))) {
			super.printJSON(new JsonMsg(2, "手机验证码输入错误！"));
			return;
		}
		if (StringUtils.isBlank(password)) {
			super.printJSON(new JsonMsg(7, "密码不能为空！"));
			return;
		}
		
		User info = new User();
		info.setPhone(phone);
		List<User> list = userService.getByUser(info);
		if (list.size() > 0) {
			super.printJSON(new JsonMsg(4, "该手机号已经存在！"));
			return;
		}
		info.setPhone(phone);
		info.setPassword(MD5.GetMD5Code(password));
		info.setCreateTime(new Date());
		info.setRegTime(new Date());
		info.setTerminal(terminal);
		info.setStatus("N");
		info.setIsnew("Y");
		info.setUsername(phone);
		info.setIsSpecial("N");
		
		if(StringUtils.isNotBlank(inviteCode)){
			User inviteUser = userService.getUserByPhone(inviteCode);
			if(inviteUser != null){
				info.setInviteCode(info.getPhone());
				frontUserService.saveOrUpdate(info);
				
				InviteRef inviteRef = new InviteRef();
				inviteRef.setUserId(info.getId());
				inviteRef.setPid(inviteUser.getId());//邀请用户id
				inviteRef.setCreateTime(new Date());
				frontUserService.saveOrUpdateInviteRef(inviteRef);
			}else{
				super.printJSON(new JsonMsg(3, "您填写的邀请码不存在"));
			}
		}else{
			info.setInviteCode(info.getPhone());
			frontUserService.saveOrUpdate(info);			
		}

		UserAccount userAccount = new UserAccount();
		userAccount.setUserId(info.getId());
		userAccount.setCreateTime(new Date());
		userAccountService.saveOrUpdate(userAccount);
		super.printJSON(new JsonMsg(-1, "注册成功！"));
	}

	/**
	 * 生成邀请码
	 * @param code 邀请码
	 * @return 
	 */
	private String generateInviteCode(String code) {
		//存在邀请码，继续生成新的邀请码，否则直接返回手机后六位为自己的邀请码
		if(checkInviteCodeExsit(code) != null){
			int intCount = 0;
			intCount = (new Random()).nextInt(999);
			if (intCount < 100) {
				intCount += 100;
			}
			code=code+intCount;//inviteCode+3位数字随机码
			generateInviteCode(code);
		}
		return code;
	}

	/**
	 * 邀请码是否存在
	 * @param code
	 * @return
	 */
	private User checkInviteCodeExsit(String code){
		User user = frontUserService.getUserByInviteCode(code);
		return user;
	}
	
	/**
	 * 用户信息接口
	 * 
	 * @param info 接受对象
	 * @throws Exception  抛出异常
	 */
	@RequestMapping(value = "/user/info")
	public void userInfo( @ModelAttribute User info) throws Exception {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		Integer id = Constant.strToInt(info.getUid());
		if (id == -1) {
			super.printJSON(new JsonMsg(1, "请先登录！"));
			return;
		}
		info.setId(Integer.valueOf(info.getUid()));
		log.info("---------------------uid="+info.getUid());
		User user = userService.getByUser(info).get(0);
		if (user == null) {
			super.printJSON(new JsonMsg(-1, "查询失败"));
			return;
		}
		HashMap<String,Integer> auth = userAuthService.getUserAuthDetail(Constant.strToInt(info.getUid()));
		jsonMap.put("auth", auth);
		jsonMap.put("user", user);
		if(auth.get("id5")==1){
			UserAuth userAuth = new UserAuth();
			userAuth.setUserId(Constant.strToInt(info.getUid()));
			userAuth.setAuthType("id5");
			jsonMap.put("myCard", userAuthService.listUserAuth(userAuth).getPageList().get(0));
		}
		super.printJSON(new JsonMsg(-1, "查询成功", jsonMap));
	}
	
	/**
	 * 用户认证接口
	 * 
	 * @param info 接受对象
	 * @throws Exception  抛出异常
	 */
	@RequestMapping(value = "/user/auth")
	public void userAuthInfo( @ModelAttribute User info) throws Exception {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		Integer id = Constant.strToInt(info.getUid());
		if (id == -1) {
			super.printJSON(new JsonMsg(1, "请先登录！"));
			return;
		}
		info.setId(id);
		User user = userService.getByUser(info).get(0);
		if (user == null) {
			super.printJSON(new JsonMsg(-1, "查询失败"));
			return;
		}
		HashMap<String,Integer> auth = userAuthService.getUserAuthDetail(Constant.strToInt(info.getUid()));
		jsonMap.put("auth", auth);
		jsonMap.put("user", user);
		if(auth.get("id5")==1){
			UserAuth userAuth = new UserAuth();
			userAuth.setUserId(Constant.strToInt(info.getUid()));
			userAuth.setAuthType("id5");
			jsonMap.put("idCard", userAuthService.listUserAuth(userAuth).getPageList().get(0));
		}
		if(auth.get("email")==1) {
			UserAuth userAuth = new UserAuth();
			userAuth.setUserId(Constant.strToInt(info.getUid()));
			userAuth.setAuthType("email");
			jsonMap.put("email", userAuthService.listUserAuth(userAuth).getPageList().get(0));
		}
		super.printJSON(new JsonMsg(-1, "查询成功", jsonMap));
	}

	/**
	 * 绑定用户信息接口
	 * @param info 接受对象
	 * @throws Exception 抛出异常
	 */
	@RequestMapping(value = "/card/bind")
	public void bindCard(@ModelAttribute UserAuth info,@RequestParam("realName") String realName) throws Exception{
		Integer id = Constant.strToInt(info.getUid());
		if (id == -1) {
			super.printJSON(new JsonMsg(1, "请先登录！"));
			return;
		}
		UserAuth idCardAuth = userAuthService.getUserAuthByIdCard(info.getAuthName());
		if (idCardAuth != null && !idCardAuth.getUserId().equals(Integer.valueOf(info.getUid()))) {
			super.printJSON(new JsonMsg(2, "身份证号已存在！"));
			return;
		}
		User user = userService.getById(id);
		user.setRealname(realName);
		userService.saveOrUpdate(user);
		info.setUserId(Integer.valueOf(info.getUid()));
		info.setAuthType("id5");
		info.setCreateTime(new Date());
		info.setAuthTime(new Date());
		UserAuth auth = new UserAuth();
		auth.setUserId(Constant.strToInt(info.getUid()));
		auth.setAuthType("id5");
		List<UserAuth> list = userAuthService.listUserAuth(auth).getPageList();
		if(list.size()>0){
			info.setId(list.get(0).getId());
		}
		userAuthService.saveOrUpdateUserAuth(info);
		super.printJSON(new JsonMsg(-1, "认证成功！"));
		return;
	}
	
	/**
	 * 绑定邮箱信息接口
	 * @param info 接受对象
	 * @throws Exception 抛出异常
	 */
	@RequestMapping(value = "/email/bind")
	public void bindEmail(@ModelAttribute UserAuth info) throws Exception{
		Integer id = Constant.strToInt(info.getUid());
		if (id == -1) {
			super.printJSON(new JsonMsg(1, "请先登录！"));
			return;
		}
		final String email = info.getAuthName();
		if(StringUtils.isBlank(email)){
			printJSON(new JsonMsg(2, "邮箱不能为空！"));
			return;
		}
		
		try {
			UserAuth auth=new UserAuth(id, "email", email);
			UserAuth authCheck = userAuthService.getAuthByUidAndType(id, "email");
			if(authCheck != null) {
				printJSON(new JsonMsg(3, "已进行过邮箱认证！"));
				return;
			}
			userAuthService.saveOrUpdateUserAuth(auth);
			super.printJSON(new JsonMsg(-1, "认证成功！"));
			return;
		} catch (Exception e) {
			e.printStackTrace();
			printJSON(new JsonMsg(0, "系统异常,请稍后再试！"));
		}
	}
	
	/**
	 * 修改登录密码
	 * @param info 接受对象
	 * @param cpassword	修改后的密码
	 * @throws Exception  抛出异常
	 */
	@RequestMapping(value = "/password/update")
	public void updatePassword( @ModelAttribute User info,@RequestParam("cpassword") String cpassword) throws Exception{
		Integer id = Constant.strToInt(info.getUid());
		if (id == -1) {
			super.printJSON(new JsonMsg(1, "请先登录！"));
			return;
		}
		if(info.getPassword()==null || info.getPassword().equals("")){
			super.printJSON(new JsonMsg(2, "请输入原始密码！"));
			return;
		}
		if(cpassword==null || cpassword.equals("")){
			super.printJSON(new JsonMsg(2, "请输入修改后密码！"));
			return;
		}
		User u = new User();
		u.setId(id);
		u = userService.getByUser(u).get(0);
		if(!u.getPassword().equals(SHA.encryptPassword(info.getPassword()))){
			super.printJSON(new JsonMsg(2, "原始密码输入错误！"));
			return;
		}
		if(u.getPassword().equals(SHA.encryptPassword(cpassword))){
			super.printJSON(new JsonMsg(2, "新密码不能与原始密码一样！"));
			return;
		}
		u.setPassword(SHA.encryptPassword(cpassword));
		userService.saveOrUpdate(u);
		super.printJSON(new JsonMsg(-1, "密码修改成功！"));
		return;
	}
	
	/**
	 * 修改交易密码
	 * @param info 接受对象
	 * @param cdealpassword	修改后的交易密码
	 * @throws Exception  抛出异常
	 */
	@RequestMapping(value = "/dealPassword/update")
	public void updateDealPassword( @ModelAttribute User info,@RequestParam("cdealpassword") String cdealpassword) throws Exception{
		Integer id = Constant.strToInt(info.getUid());
		if (id == -1) {
			super.printJSON(new JsonMsg(1, "请先登录！"));
			return;
		}
		User u = new User();
		u.setId(id);
		List<User> list = userService.getByUser(u);
		if(list.size()==0){
			super.printJSON(new JsonMsg(3, "用户不存在"));
			return;
		}
		u = list.get(0);
		if(u.getDealPassword()!=null && !u.getDealPassword().equals("")){
			if(info.getDealPassword()==null || info.getDealPassword().equals("")){
				super.printJSON(new JsonMsg(2, "请输入原始交易密码！"));
				return;
			}
			if(cdealpassword==null || cdealpassword.equals("")){
				super.printJSON(new JsonMsg(2, "请输入修改后交易密码！"));
				return;
			}
			
			if(!u.getDealPassword().equals(SHA.encryptPassword(info.getDealPassword()))){
				super.printJSON(new JsonMsg(2, "原始交易密码输入错误！"));
				return;
			}
			if(u.getDealPassword().equals(SHA.encryptPassword(cdealpassword))){
				super.printJSON(new JsonMsg(2, "新密码不能与原始交易密码一样！"));
				return;
			}
		}
		u.setDealPassword(SHA.encryptPassword(cdealpassword));
		userService.saveOrUpdate(u);
		super.printJSON(new JsonMsg(-1, "密码修改成功！"));
		return;
	}
	/**
	 * 用户基本信息修改接口
	 * 
	 * @param info 接受对象
	 * @throws Exception  抛出异常
	 */
	@RequestMapping(value = "/user/update")
	public void updateUser( @ModelAttribute User info) throws Exception {
		Integer id = Constant.strToInt(info.getUid());
		if (id == -1) {
			super.printJSON(new JsonMsg(1, "请先登录！"));
			return;
		}
		info.setId(id);
		//有安全风险,先屏蔽该方法
		//userService.saveOrUpdate(info);
		super.printJSON(new JsonMsg(-1, "用户资料修改成功"));
	}

	/**
	 * 解绑银行卡
	 * @param info	接受对象
	 * @throws Exception	抛出异常
	 */
	@RequestMapping(value = "/bank/delete")
	public void deleteBank( @ModelAttribute BankCard info) throws Exception {
		Integer uid = Constant.strToInt(info.getUid());
		super.printJSON(new JsonMsg(1, "由于第三方支付限制，不能解绑银行卡！"));
		return;
		/*if (uid == -1) {
			super.printJSON(new JsonMsg(1, "请先登录！"));
			return;
		}
		bankCardService.delete(info.getId());
		super.printJSON(new JsonMsg(-1, "解绑成功！"));*/
	}
	
	/**
	 * 我的银行卡
	 * @param info 接受对象
	 * @throws Exception  抛出异常
	 */
	@RequestMapping(value = "/bank/my")
	public void MyBank( @ModelAttribute BankCardVo info) throws Exception{
		Integer uid = Constant.strToInt(info.getUid());
		if (uid == -1) {
			super.printJSON(new JsonMsg(1, "请先登录！"));
			return;
		}
		info.setUserId(uid);
		super.printJSON(new JsonMsg(-1, "我的银行卡查询成功",bankCardService.listAll(info)));
	}
	
	/**
	 * 我的红包
	 * @param info	uid必传,status(-1,过期;0,未使用;1,使用)
	 * @throws Exception
	 */
	@RequestMapping(value = "/red/my")
	public void myRed(@ModelAttribute RedEnveVo info) throws Exception{
		Integer uid = Constant.strToInt(info.getUid());
		if (uid == -1) {
			super.printJSON(new JsonMsg(1, "请先登录！"));
			return;
		}
		info.setUid(info.getUid());
		super.printJSON(new JsonMsg(-1, "我的红包查询成功",redEnveService.list(info)));
		return;
	}
	
	
	private Integer getUid(String phone){
		User user = new User();
		user.setPhone(phone);
		List<User> list = userService.getByUser(user);
		return list.get(0).getId();
	}
	
	/**
	 * 获取用户的还款详情
	 * @param tenderId
	 * @param borrowId
	 * @param userId
	 * @return
	 */
	@RequestMapping("/repay/detail")
	public String showPayDetail(@RequestParam("tenderId") Integer tenderId,
								@RequestParam("borrowId") Integer borrowId,
							    @RequestParam("userId") Integer userId){
		try {
			List<BorrowPaymentDetailVo> detailList=borrowPaymentDetailService.detailByBorrowIdAndUserId(tenderId,borrowId, userId);
			super.printJSON(new JsonMsg(-1, "操作成功", detailList));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 获取系统参数
	 * @param uid
	 * @param money
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/system/config")
	public String getSystemConfig(@RequestParam(value="uid",required=false) Integer uid,
								  @RequestParam(value="money",required=false) Double money,
								  @RequestParam(value="terminal",required=false)String terminal) throws Exception{
		
		SystemConfig listConfig=systemService.listSystemConfig();
		if(listConfig==null ){
			super.printJSON(new JsonMsg(0, "系统错误，请联系管理员!"));
		}else{
			super.printJSON(new JsonMsg(-1, "操作成功", listConfig));
		}
		return null;
	}
	
	@RequestMapping("/user/code")
	public String userIviteCode(@RequestParam("uid") Integer uid) throws Exception{
		User user=userService.getById(uid);
		if(user==null){
			super.printJSON(new JsonMsg(0, "请先登录!"));
			return null;
		}
		String code="";
		if(StringUtils.isNotBlank(user.getInsideInviteCode())){
			code=user.getInsideInviteCode();
		}else{
			code=user.getInviteCode();
		}
		super.printJSON(new JsonMsg(-1, "操作成功",code));
		return null;
	}
	
	/**
	 * 发送忘记密码短信
	 * @param model
	 * @param phone
	 * @throws Exception
	 */
	@RequestMapping(value="/send",method = RequestMethod.POST)
	public void send(Model model, 
			@ModelAttribute User info) throws Exception {
		Map<String, String> jsonMap = new HashMap<String, String>();
		if (info.getPhone() == null || StringUtils.isBlank(info.getPhone())) {
			printJSON(new JsonMsg(1, "手机号不能为空！"));
			return;
		}
		User user = userService.selectByNameOrPhone(info.getPhone());
		if(user == null) {
			printJSON(new JsonMsg(2, "手机号不存在！"));
			return;
		}
		String imgCode = request.getParameter("imgCode");
		if(StringUtils.isBlank(imgCode)) {
			super.printJSON(new JsonMsg(1, "图形验证码不能为空！"));
			return;
		}
		String sessionCode = (String) request.getSession().getAttribute("jcaptchaCode");
		if(!imgCode.equals(sessionCode)) {
			super.printJSON(new JsonMsg(5, "图形验证码输入有误！"));
			return;
		}
		int intCount = 0;
		intCount = new Random().nextInt(9999);
		if (intCount < 1000) {
			intCount += 1000;
		}
		String randomCode = "" + intCount;
		sMSService.sendForgetPwdSms(info.getPhone(), randomCode);
		//String randomCode="0000";
		// md5加密验证码给前台
		jsonMap.put("randomCode", SHA.encryptPassword(randomCode));
		jsonMap.put("phone", info.getPhone());
		super.printJSON(new JsonMsg(-1, "发送成功！",jsonMap));
	}
	
	/**
	 * 修改密码
	 * @param phone
	 * @param code
	 * @param randomCode
	 * @param password
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/pwd/update",method=RequestMethod.POST)
	public String updateUserPwd(@RequestParam("phone") String phone,
								@RequestParam("code") String code,
								@RequestParam("randomCode") String randomCode,
								@RequestParam("password") String password) throws Exception{
		if(StringUtils.isBlank(phone)){
			printJSON(new JsonMsg(1, "手机号码不能为空"));
			return null;
		}		
		if(StringUtils.isBlank(code)){
			printJSON(new JsonMsg(2, "验证码不能为空"));
			return null;
		}else{
			if(!SHA.encryptPassword(code).equals(randomCode)){
				printJSON(new JsonMsg(3, "验证码错误"));
				return null;				
			}
		}
		
		if(StringUtils.isBlank(password)){
			printJSON(new JsonMsg(4, "密码不能为空"));
			return null;
		}	
		User temp=new User();
		temp.setPhone(phone);
		List<User> listUser=userService.getByUser(temp);
		if(listUser!=null){
			temp=listUser.get(0);
			temp.setPassword(MD5.GetMD5Code(password));
			userService.saveOrUpdate(temp);
			printJSON(new JsonMsg(-1, "操作成功"));
		}else{
			printJSON(new JsonMsg(5, "系统异常,请稍后再试!"));
		}
		
		return null;
	}
	
	/**
	 * 发送找回交易密码短信
	 * @param model
	 * @param phone
	 * @throws Exception
	 */
	@RequestMapping(value="/find/send",method = RequestMethod.POST)
	public void findSend(Model model, 
			@RequestParam("phone") String phone) throws Exception {
		Map<String, String> jsonMap = new HashMap<String, String>();
		if (phone == null || StringUtils.isBlank(phone)) {
			printJSON(new JsonMsg(1, "手机号不能为空！"));
			return;
		}
		User user = userService.selectByNameOrPhone(phone);
		if(user == null) {
			printJSON(new JsonMsg(2, "手机号不存在！"));
			return;
		}
		int intCount = 0;
		intCount = new Random().nextInt(9999);
		if (intCount < 1000) {
			intCount += 1000;
		}
		String randomCode = "" + intCount;
		sMSService.sendForgetPwdSms(phone, randomCode);
		// md5加密验证码给前台
		jsonMap.put("randomCode", SHA.encryptPassword(randomCode));
		jsonMap.put("phone", phone);
		super.printJSON(new JsonMsg(-1, "发送成功！",jsonMap));
	}
	
	/**
	 * 修改交易密码
	 * @param phone
	 * @param code
	 * @param randomCode
	 * @param password
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/deal/pwd/update",method=RequestMethod.POST)
	public String updateUserDealPwd(@RequestParam("phone") String phone,
			@RequestParam("code") String code,
			@RequestParam("randomCode") String randomCode,
			@RequestParam("password") String password) throws Exception{
		if(StringUtils.isBlank(phone)){
			printJSON(new JsonMsg(1, "手机号码不能为空"));
			return null;
		}		
		if(StringUtils.isBlank(code)){
			printJSON(new JsonMsg(2, "验证码不能为空"));
			return null;
		}else{
			if(!SHA.encryptPassword(code).equals(randomCode)){
				printJSON(new JsonMsg(3, "验证码错误"));
				return null;				
			}
		}
		
		if(StringUtils.isBlank(password)){
			printJSON(new JsonMsg(4, "交易密码不能为空"));
			return null;
		}	
		User temp=new User();
		temp.setPhone(phone);
		List<User> listUser=userService.getByUser(temp);
		if(listUser!=null){
			temp=listUser.get(0);
			temp.setDealPassword(MD5.GetMD5Code(password));
			userService.saveOrUpdate(temp);
			printJSON(new JsonMsg(-1, "操作成功"));
		}else{
			printJSON(new JsonMsg(5, "系统异常,请稍后再试!"));
		}
		
		return null;
	}
	
	/**
	 * 根据uid生成二维码
	 * @param uid
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/user/qrCode")
	public String QRcode(@RequestParam("uid") Integer uid ) throws Exception{
		if (uid == -1) {
			super.printJSON(new JsonMsg(1, "请先登录！"));
			return null;
		}
		User user=userService.getById(uid);
		if(user==null){
			super.printJSON(new JsonMsg(0, "请先登录!"));
			return null;
		}
		String code="";
		if(StringUtils.isNotBlank(user.getInsideInviteCode())){
			code=user.getInsideInviteCode();
		}else{
			code=user.getInviteCode();
		}		
		String path=QRcode.generateCode(request, "http://www.panyijr.cn/wx_py/reg.html#"+code);
		printJSON(new JsonMsg(-1, "操作成功",path.substring(path.indexOf("/static/"), path.length())));
		
		return null;
	}
	
	/**
	 * 提现所需的用户信息
	 * @param uid 用户id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/withdraw/info")
	public void withdrawInfo(@RequestParam("uid") Integer uid ) throws Exception{
		User user = userService.getById(uid);
		if(user == null) {
			super.printJSON(new JsonMsg(1, "请登录后再试！"));
			return;
		}
		UserAccount account = userAccountService.getByUserId(uid);
		BankCardVo vo = new BankCardVo();
		vo.setUserId(uid);
		
		List<BankCardVo> list = bankCardService.listDefaultCard(vo);
		if(list != null && list.size() > 0) {
			vo = list.get(0);
		}
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("user", user);
		result.put("account", account);
		result.put("bankCard", vo);
		super.printJSON(new JsonMsg(-1, "获取提现信息成功！", result));
		return;
	}
	
	/**
	 * 获取用户的邀请信息
	 * @param uid 用户id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/invite/list")
	public void inviteList(@ModelAttribute InviteRefVo info) throws Exception{
		Integer id = Constant.strToInt(info.getUid());
		if (id == -1) {
			super.printJSON(new JsonMsg(1, "请先登录！"));
			return;
		}
		Map<String, Object> result = new HashMap<String, Object>();
		User user = userService.getById(id) ;
		info.setPid(id);
		PageInfo<InviteRefVo> pageInfo =  userService.listInviteRef(info);
		Double amount = fundRecordService.sumInviteReward(id);
		amount = amount == null?0.0:amount;
		result.put("user", user);
		result.put("pageInfo", pageInfo);
		result.put("amount", amount);
		super.printJSON(new JsonMsg(-1, "获取成功！",result));
	}
	
	/**
	 * 获取实名认证信息
	 * @param uid
	 * @throws Exception
	 */
	@RequestMapping("/realname/get")
	public void getRealname(@RequestParam(value="uid") String uid) throws Exception{
		Integer id = Constant.strToInt(uid);
		if (id == -1) {
			super.printJSON(new JsonMsg(1, "请先登录！"));
			return;
		}
		User user = userService.getById(id);
		UserAuth auth = userAuthService.getAuthByUidAndType(id, "id5");
		Map<String, Object> result = new HashMap<String, Object>();
		String realname = user.getRealname() == null ? "" : user.getRealname();
		String cardNo = auth == null ? "" : auth.getAuthName();
		result.put("realname", realname);
		result.put("cardNo", cardNo);
		super.printJSON(new JsonMsg(-1, "获取成功！", result));
	}
	
	/**
	 * 实名认证
	 * @param uid
	 * @param realname
	 * @param cardNo
	 * @throws Exception
	 */
	@RequestMapping("/user/realname")
	public void userRealname(@RequestParam(value="uid") String uid,
							@RequestParam(value="realname") String realname,
							@RequestParam(value="cardNo") String cardNo) throws Exception{
		Integer id = Constant.strToInt(uid);
		if (id == -1) {
			super.printJSON(new JsonMsg(1, "请先登录！"));
			return;
		}
		if(StringUtils.isBlank(realname)) {
			super.printJSON(new JsonMsg(1, "请输入真实姓名！"));
			return;
		}
		if(StringUtils.isBlank(cardNo)) {
			super.printJSON(new JsonMsg(1, "请输入身份证号码！"));
			return;
		}
		User user = userService.getById(id);
		int flag = 0;
		if(realname.equals(user.getRealname())) {
			flag++;
		}
		UserAuth auth = userAuthService.getAuthByUidAndType(id, "id5");
		if(auth != null) {
			if(cardNo.equals(auth.getAuthName())) {
				flag++;
			}
		}else {
			auth = new UserAuth();
		}
		if(flag == 2) {
			super.printJSON(new JsonMsg(-1, "实名认证成功！"));
		}else {
			user.setRealname(realname);
			int item = userService.saveOrUpdate(user);
			auth.setUserId(id);
			auth.setAuthName(cardNo);
			auth.setAuthType("id5");
			auth.setAuthTime(new Date());
			auth.setCreateTime(new Date());
			item += userAuthService.saveOrUpdateUserAuth(auth);
			if(item == 2) {
				super.printJSON(new JsonMsg(-1, "实名认证成功！"));
			}else {
				super.printJSON(new JsonMsg(1, "实名认证失败！"));
			}
		}
	}
	
	
	/**
	 * 绑定手机号码
	 * 
	 * @param info 接受对象
	 * @throws Exception  抛出异常
	 */
	@RequestMapping(value = "/user/bindphone")
	public void bindphone(@RequestParam(value="uid") String uid,
			@RequestParam(value="phone") String phone,
			@RequestParam(value="code") String code,
			@RequestParam(value="randomCode") String randomCode) throws Exception {
		Integer id = Constant.strToInt(uid);
		if (id == 0 || id == null || id.equals("")) {
			super.printJSON(new JsonMsg(1, "请先登录！"));
			return;
		}
		
		if (StringUtils.isBlank(phone)) {
			super.printJSON(new JsonMsg(3, "手机号不能为空！"));
			return;
		}		
		if(code==null || code.equals("")){
			super.printJSON(new JsonMsg(1, "请填写验证码！"));
			return;
		}
		if (!randomCode.equals(SHA.encryptPassword(code+phone))) {
			super.printJSON(new JsonMsg(2, "手机验证码输入错误！"));
			return;
		}
			
		User info = new User();
		info.setPhone(phone);
		List<User> list = userService.getByUser(info);
		if (list.size() > 0) {
			super.printJSON(new JsonMsg(4, "该手机号已经存在！"));
			return;
		}
		
		info.setId(id);
		userService.saveOrUpdate(info);
		super.printJSON(new JsonMsg(-1, "手机绑定成功"));
		return;
	}
	
	
	/**
	 * 获得银行卡信息
	 * @param uid
	 * @throws Exception
	 */
	@RequestMapping("/bankCard/get")
	public void bankCardBind(@RequestParam(value="uid") String uid) throws Exception {
		Integer id = Constant.strToInt(uid);
		if (id == -1) {
			super.printJSON(new JsonMsg(1, "请先登录！"));
			return;
		}
		List<Bank> banks = bankCardService.listBack();
		Map<String, Object> result = new HashMap<String, Object>();
		//银行卡绑定
		try {
			List<BankCard> bankCards = bankCardService.listCardByUserId(id);
			BankCard bankCard = null;
			if(bankCards != null && bankCards.size()>0) {
				bankCard = bankCards.get(0);
				//根据城市编码获取城市名称
				List<City> cityList = cityService.getCityAndPCityBYCode(bankCard.getCityCode());
				for(City city : cityList){
					if(-1==city.getPid()){
						result.put("province", city.getCode());
					}else{
						result.put("bankCityName", city.getName());
					}
				}
				result.put("city", bankCard.getCityCode());
			}
			result.put("bankCard", bankCard);
			result.put("banks", banks);
			super.printJSON(new JsonMsg(-1, "获取成功！", result));
		} catch (Exception e) {
			super.printJSON(new JsonMsg(0, "获取失败！"));
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 银行卡绑定
	 * @param cityCode
	 * @param bankCode
	 * @param cardNo
	 * @throws Exception
	 */
	@RequestMapping("/bankCard/bind")
	public void bankCardBind(@RequestParam(value="uid") String uid,
			@RequestParam(value="cityCode")String cityCode,
			@RequestParam(value="bankCode")String bankCode,
			@RequestParam(value="cardNo")String cardNo,
			@RequestParam(value="terminal", required=false, defaultValue="WX")String terminal) throws Exception {
		Integer id = Constant.strToInt(uid);
		if (id == -1) {
			super.printJSON(new JsonMsg(1, "请先登录！"));
			return;
		}
		if(StringUtils.isBlank(cityCode)) {
			super.printJSON(new JsonMsg(1, "请选择开户城市！"));
			return;
		}
		if(StringUtils.isBlank(bankCode)) {
			super.printJSON(new JsonMsg(1, "请选择开户银行！"));
			return;
		}
		if(StringUtils.isBlank(cardNo)) {
			super.printJSON(new JsonMsg(1, "请输入银行卡号！"));
			return;
		}
		User user = userService.getById(id);
		//删除用户曾经绑定的银行卡
		int i = bankCardService.deleteByUserId(user.getId());
		if(i < 0) {
			super.printJSON(new JsonMsg(2, "银行卡绑定失败！删除旧银行卡错误！"));
			return;
		}
		//添加银行卡
		BankCard bankCard = new BankCard();
		bankCard.setUserId(user.getId());
		bankCard.setBankName(bankCode);
		bankCard.setCityCode(cityCode);
		bankCard.setCardNo(cardNo);
		bankCard.setTerminal(terminal);
		bankCard.setIsDelete(0);
		bankCard.setCreateTime(new Date());
		int item = bankCardService.saveOrUpdate(bankCard);
		if(item <= 0) {
			super.printJSON(new JsonMsg(2, "银行卡绑定失败！保存或更新银行卡发生错误！"));
			return;
		}
		super.printJSON(new JsonMsg(-1, "银行卡绑定成功！"));
	}
	
	/**
	 * 设置富友密码
	 * @param uid
	 * @param loginPassword
	 * @param payPassword
	 * @throws Exception
	 */
	@RequestMapping("/fuion/pwd")
	public void fuioPwd(@RequestParam(value="uid") String uid,
						@RequestParam(value="loginPassword")String loginPassword,
						@RequestParam(value="payPassword")String payPassword) throws Exception {
		Integer id = Constant.strToInt(uid);
		if (id == -1) {
			super.printJSON(new JsonMsg(1, "请先登录！"));
			return;
		}
		if(StringUtils.isBlank(loginPassword)) {
			super.printJSON(new JsonMsg(1, "请输入富友登录密码！"));
			return;
		}
		if(StringUtils.isBlank(payPassword)) {
			super.printJSON(new JsonMsg(1, "请输入富友交易密码！"));
			return;
		}
		User user = userService.getById(id);
		int flag = 0;
		if(MD5.GetMD5Code(loginPassword).equals(user.getLoginPassword())) {
			flag++;
		}
		if(MD5.GetMD5Code(payPassword).equals(user.getDealPassword())) {
			flag++;
		}
		if(flag == 2) {
			super.printJSON(new JsonMsg(-1, "设置密码成功！"));
			return;
		}
		user.setDealPassword(MD5.GetMD5Code(payPassword));
		user.setLoginPassword(MD5.GetMD5Code(loginPassword));
		int item = userService.saveOrUpdate(user);
		if(item <= 0) {
			super.printJSON(new JsonMsg(1, "设置密码失败！"));
			return;
		}
		super.printJSON(new JsonMsg(-1, "设置密码成功！"));
	}
}
